// V-backend/src/middleware/auth.js
const jwt = require('jsonwebtoken');
const { Audience, Anchor } = require('../models');

const auth = async (req, res, next) => {
  try {
    console.log('🔐 开始认证检查...');
    console.log('📝 请求头 Authorization:', req.header('Authorization'));
    
    // 从请求头获取token
    const authHeader = req.header('Authorization');
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      console.log('❌ 未提供有效的Authorization头');
      return res.status(401).json({
        code: 401,
        success: false,
        message: '访问被拒绝，请提供有效的token'
      });
    }

    const token = authHeader.replace('Bearer ', '');
    
    if (!token) {
      console.log('❌ Token为空');
      return res.status(401).json({
        code: 401,
        success: false,
        message: '访问被拒绝，请提供token'
      });
    }

    console.log('🔑 验证token:', token.substring(0, 20) + '...');
    
    // 验证token
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    console.log('✅ Token解码成功:', decoded);
    
    let user;
    // 根据用户类型查找用户
    if (decoded.userType === 'audience') {
      console.log('👤 查找观众用户 ID:', decoded.userId);
      user = await Audience.findByPk(decoded.userId);
    } else if (decoded.userType === 'anchor') {
      console.log('👤 查找主播用户 ID:', decoded.userId);
      user = await Anchor.findByPk(decoded.userId);
    } else {
      console.log('❌ 未知用户类型:', decoded.userType);
      return res.status(401).json({
        code: 401,
        success: false,
        message: '无效的用户类型'
      });
    }

    if (!user) {
      console.log('❌ 用户不存在');
      return res.status(401).json({
        code: 401,
        success: false,
        message: '用户不存在'
      });
    }

    // 将用户信息添加到请求对象
    req.user = {
      userId: decoded.userId,
      userType: decoded.userType,
      anchor_id: decoded.userType === 'anchor' ? decoded.userId : undefined,
      audience_id: decoded.userType === 'audience' ? decoded.userId : undefined,
      role: user.role // 添加角色信息
    };

    console.log('✅ 认证成功，用户ID:', decoded.userId, '类型:', decoded.userType, '角色:', user.role);
    next();
  } catch (error) {
    console.error('❌ Token验证错误:', error);
    
    if (error.name === 'JsonWebTokenError') {
      console.log('❌ JWT格式错误');
      return res.status(401).json({
        code: 401,
        success: false,
        message: '无效的token'
      });
    }
    
    if (error.name === 'TokenExpiredError') {
      console.log('❌ Token已过期');
      return res.status(401).json({
        code: 401,
        success: false,
        message: 'token已过期，请重新登录'
      });
    }

    console.error('❌ 其他认证错误:', error);
    res.status(500).json({
      code: 500,
      success: false,
      message: '服务器错误'
    });
  }
};

// 管理后台专用认证 - 只允许主播访问
const adminAuth = async (req, res, next) => {
  try {
    console.log('👨‍💼 管理后台认证检查...');
    
    const authHeader = req.header('Authorization');
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return res.status(401).json({
        code: 401,
        success: false,
        message: '访问被拒绝，请先登录'
      });
    }

    const token = authHeader.replace('Bearer ', '');
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    
    // 检查用户类型必须是主播
    if (decoded.userType !== 'anchor') {
      return res.status(403).json({
        code: 403,
        success: false,
        message: '权限不足，只有主播可以访问管理后台'
      });
    }

    // 验证主播用户是否存在
    const anchor = await Anchor.findByPk(decoded.userId);
    if (!anchor) {
      return res.status(401).json({
        code: 401,
        success: false,
        message: '主播用户不存在'
      });
    }

    req.user = {
      userId: decoded.userId,
      userType: decoded.userType,
      anchor_id: decoded.userId,
      role: anchor.role // 添加角色信息
    };

    console.log('✅ 管理后台认证成功，主播ID:', decoded.userId, '角色:', anchor.role);
    next();
  } catch (error) {
    console.error('❌ 管理后台认证错误:', error);
    res.status(401).json({
      code: 401,
      success: false,
      message: '认证失败'
    });
  }
};

module.exports = { auth, adminAuth };